<template>
  <div>
    <h2>采购管理</h2>
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-input v-model="searchForm.supplier" placeholder="供应商" style="width: 80px;"></el-input>
      <el-input v-model="searchForm.productName" placeholder="商品名" style="width: 80px;"></el-input>
      <!-- 采购数量范围 -->
      <el-input v-model="searchForm.purchaseQuantityMin" placeholder="数量最小值" style="width: 100px;"></el-input>
      <el-input v-model="searchForm.purchaseQuantityMax" placeholder="数量最大值" style="width: 100px;"></el-input>
      <!-- 采购金额范围 -->
      <el-input v-model="searchForm.purchaseAmountMin" placeholder="金额最小值" style="width: 100px;"></el-input>
      <el-input v-model="searchForm.purchaseAmountMax" placeholder="金额最大值" style="width: 100px;"></el-input>
      <!-- 采购状态选择框 -->
      <el-select v-model="searchForm.purchaseStatus" placeholder="状态" style="width: 80px;">
        <el-option label="待审批" value="0"></el-option>
        <el-option label="已审批" value="1"></el-option>
        <el-option label="已完成" value="2"></el-option>
      </el-select>
      <!-- 采购时间范围 -->
      <el-date-picker 
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="handleDateChange">
      </el-date-picker>
      <el-button class="blue-button" @click="fetchPurchaseList">查询</el-button>
      <el-button class="red-button" @click="clearSearchForm">清空条件</el-button>
      <!-- 采购按钮 -->
      <el-button class="blue-button" @click="openPurchaseDialog">采购</el-button>
    </div>
    <!-- 使用 ElTable 替代原生 table -->
    <el-table
      :data="purchaseList"
      stripe
      hover-effect
      border
      style="width: 100%">
        <!-- 移除采购 ID 列 -->
        <!-- <el-table-column prop="purchaseId" label="采购 ID"></el-table-column> -->
        <el-table-column prop="supplier" label="供应商"></el-table-column>
        <el-table-column prop="supplierPhone" label="供应商电话"></el-table-column>
        <el-table-column prop="productName" label="商品名称"></el-table-column>
        <!-- 新增商品单价列 -->
        <el-table-column prop="unitPrice" label="商品单价"></el-table-column>
        <!-- 新增采购商品单位列 -->
        <el-table-column prop="productUnit" label="商品单位"></el-table-column>
        
        <el-table-column prop="purchaseQuantity" label="采购数量"></el-table-column>
        <el-table-column prop="purchaseAmount" label="采购金额"></el-table-column>
        <el-table-column prop="purchaseTime" label="采购时间"></el-table-column>
        <!-- 采购状态列 -->
        <el-table-column label="采购状态">
          <template #default="scope">
            <div v-if="userInfo.userRole === 0 && scope.row.purchaseStatusText!== '已完成'">
              <el-select
                v-model="scope.row.purchaseStatusText"
                @change="handleStatusChange(scope.row)"
                placeholder="选择状态" style="width: 100px;">
                <el-option label="待审批" value="待审批"></el-option>
                <el-option label="已审批" value="已审批"></el-option>
                <el-option label="已完成" value="已完成"></el-option>
              </el-select>
            </div>
            <span v-else>{{ scope.row.purchaseStatusText }}</span>
          </template>
        </el-table-column>
        <!-- 修改按钮列 -->
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.purchaseStatus === 0"
              type="primary"
              @click="openEditDialog(scope.row)">
              修改
            </el-button>
          </template>
        </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <!-- 采购弹窗 -->
    <el-dialog v-model="purchaseDialogVisible" 
      title="发起采购"
      @close="resetPurchaseForm">
        <el-form :model="purchaseForm" :rules="purchaseRules" ref="purchaseFormRef">
          <el-form-item label="供应商" prop="supplier">
            <el-input v-model="purchaseForm.supplier"></el-input>
          </el-form-item>
          <el-form-item label="供应商电话" prop="supplierPhone">
            <el-input v-model="purchaseForm.supplierPhone"></el-input>
          </el-form-item>
          <el-form-item label="采购商品" prop="productName">
            <el-input v-model="purchaseForm.productName"></el-input>
          </el-form-item>
          <!-- 新增商品单价表单项 -->
          <el-form-item label="商品单价" prop="unitPrice">
            <el-input v-model.number="purchaseForm.unitPrice"></el-input>
          </el-form-item>
          <!-- 新增采购商品单位表单项 -->
          <el-form-item label="商品单位" prop="productUnit">
            <el-input v-model="purchaseForm.productUnit"></el-input>
          </el-form-item>
          
          <el-form-item label="采购数量" prop="purchaseQuantity">
            <el-input v-model.number="purchaseForm.purchaseQuantity"></el-input>
          </el-form-item>
        </el-form>
      <template #footer>
        <el-button @click="closePurchaseDialog">取消</el-button>
        <el-button type="primary" @click="submitPurchaseForm">确定</el-button>
      </template>
    </el-dialog>
    <!-- 修改弹窗 -->
    <el-dialog v-model="editDialogVisible" 
      title="修改采购信息"
      @close="resetEditForm">
        <el-form :model="editForm" :rules="purchaseRules" ref="editFormRef">
          <el-form-item label="供应商" prop="supplier">
            <el-input v-model="editForm.supplier"></el-input>
          </el-form-item>
          <el-form-item label="供应商电话" prop="supplierPhone">
            <el-input v-model="editForm.supplierPhone"></el-input>
          </el-form-item>
          <el-form-item label="采购商品" prop="productName">
            <el-input v-model="editForm.productName"></el-input>
          </el-form-item>
          <!-- 新增商品单价表单项 -->
          <el-form-item label="商品单价" prop="unitPrice">
            <el-input v-model.number="editForm.unitPrice"></el-input>
          </el-form-item>
          <!-- 新增采购商品单位表单项 -->
          <el-form-item label="商品单位" prop="productUnit">
            <el-input v-model="editForm.productUnit"></el-input>
          </el-form-item>
          
          <el-form-item label="采购数量" prop="purchaseQuantity">
            <el-input v-model.number="editForm.purchaseQuantity"></el-input>
          </el-form-item>
          <el-form-item label="采购状态" prop="purchaseStatus">
            <el-select v-model="editForm.purchaseStatusText" placeholder="选择状态">
              <el-option label="待审批" value="待审批"></el-option>
              <el-option label="已审批" value="已审批"></el-option>
              <el-option label="已完成" value="已完成"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      <template #footer>
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, ref as formRef, defineProps } from 'vue';
import request from '../utils/request'; 
import { ElPagination, ElInput, ElButton, ElDatePicker, ElTable, ElTableColumn, ElDialog, ElForm, ElFormItem, ElSelect, ElOption, ElMessage } from 'element-plus';
import dayjs from 'dayjs';

// 接收父组件传递的用户信息
const props = defineProps({
  userInfo: {
    type: Object,
    default: () => ({})
  }
});
const purchaseList = ref([]);
const currentPage = ref(1); 
const pageSize = ref(10); 
const total = ref(0); 
// 更新搜索表单数据结构，添加 purchaseStatus 字段
const searchForm = ref({
  page: currentPage.value,
  pageSize: pageSize.value,
  supplier: '',
  productName: '',
  purchaseQuantityMin: '',
  purchaseQuantityMax: '',
  purchaseAmountMin: '',
  purchaseAmountMax: '',
  startDate: '',
  endDate: '',
  purchaseStatus: '' // 新增采购状态字段
});
const dateRange = ref([]);

const purchaseDialogVisible = ref(false);
// 在采购表单中添加 productUnit 和 unitPrice 字段
const purchaseForm = reactive({
  supplier: '',
  supplierPhone: '',
  productName: '',
  productUnit: '', // 新增商品单位字段
  unitPrice: 0, // 新增商品单价字段
  purchaseQuantity: 0
});
// 添加商品单位和商品单价的表单验证规则
const purchaseRules = {
  supplier: [
    { required: true, message: '请输入供应商', trigger: 'blur' }
  ],
  supplierPhone: [
    { required: true, message: '请输入供应商电话', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入采购商品', trigger: 'blur' }
  ],
  productUnit: [
    { required: true, message: '请输入商品单位', trigger: 'blur' }
  ],
  unitPrice: [
    { required: true, message: '请输入商品单价', trigger: 'blur' },
    { type: 'number', message: '商品单价必须为数字', trigger: 'blur' }
  ],
  purchaseQuantity: [
    { required: true, message: '请输入采购数量', trigger: 'blur' },
    { type: 'number', message: '采购数量必须为数字', trigger: 'blur' }
  ]
};
const purchaseFormRef = formRef(null);

const editDialogVisible = ref(false);
const editForm = reactive({
  purchaseId: null, // 记录要修改的采购记录的 ID
  supplier: '',
  supplierPhone: '',
  productName: '',
  productUnit: '',
  unitPrice: 0,
  purchaseQuantity: 0,
  purchaseStatusText: '待审批'
});
const editFormRef = formRef(null);

const handleDateChange = (value) => {
  if (value && value.length === 2) {
    searchForm.value.startDate = dayjs(value[0]).format('YYYY-MM-DD');
    searchForm.value.endDate = dayjs(value[1]).format('YYYY-MM-DD');
  } else {
    searchForm.value.startDate = '';
    searchForm.value.endDate = '';
  }
};

const fetchPurchaseList = async () => {
  try {
    searchForm.value.page = currentPage.value;
    searchForm.value.pageSize = pageSize.value;
    console.log('开始请求采购记录，参数:', searchForm.value);
    const response = await request.get('/purchase_record/getPurchaseRecords', {
      params: searchForm.value // 传递包含采购状态的搜索表单数据
    });
    console.log('采购记录请求成功，响应数据:', response.data);
    const list = response.data.list.map(item => ({
      ...item,
      purchaseStatusText: getPurchaseStatusText(item.purchaseStatus)
    }));
    purchaseList.value = list;
    total.value = response.data.total;
  } catch (error) {
    console.error('获取采购记录失败:', error);
  }
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchPurchaseList();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchPurchaseList();
};

const clearSearchForm = () => {
  searchForm.value = {
    page: 1,
    pageSize: 10,
    supplier: '',
    productName: '',
    purchaseQuantityMin: '',
    purchaseQuantityMax: '',
    purchaseAmountMin: '',
    purchaseAmountMax: '',
    startDate: '',
    endDate: '',
    purchaseStatus: '' // 清空采购状态
  };
  dateRange.value = [];
  currentPage.value = 1;
  pageSize.value = 10;
  fetchPurchaseList();
};

const openPurchaseDialog = () => {
  purchaseDialogVisible.value = true;
  console.log(purchaseDialogVisible.value);
};

const closePurchaseDialog = () => {
  purchaseDialogVisible.value = false;
  resetPurchaseForm();
};

const resetPurchaseForm = () => {
  purchaseForm.supplier = '';
  purchaseForm.supplierPhone = '';
  purchaseForm.productName = '';
  purchaseForm.productUnit = ''; // 重置商品单位
  purchaseForm.unitPrice = 0; // 重置商品单价
  purchaseForm.purchaseQuantity = 0;
};

const submitPurchaseForm = async () => {
  purchaseFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        console.log('开始提交采购表单，表单数据:', purchaseForm);
        const response = await request.post('/purchase_record/addPurchaseRecord', purchaseForm);
        console.log('采购表单提交成功，响应数据:', response.data);
        if (response.data.code === 1) {
          ElMessage.success('采购成功，等待审批');
          closePurchaseDialog();
          fetchPurchaseList();
        } else {
          ElMessage.error('采购失败');
          console.error('采购失败:', response.data.message);
        }
      } catch (error) {
        ElMessage.error('采购失败');
        console.error('采购失败:', error);
      }
    }
  });
};

const openEditDialog = (row) => {
  editDialogVisible.value = true;
  editForm.purchaseId = row.purchaseId; 
  editForm.supplier = row.supplier;
  editForm.supplierPhone = row.supplierPhone;
  editForm.productName = row.productName;
  editForm.productUnit = row.productUnit;
  editForm.unitPrice = row.unitPrice;
  editForm.purchaseQuantity = row.purchaseQuantity;
  editForm.purchaseStatusText = getPurchaseStatusText(row.purchaseStatus);
};

const closeEditDialog = () => {
  editDialogVisible.value = false;
  resetEditForm();
};

const resetEditForm = () => {
  editForm.purchaseId = null;
  editForm.supplier = '';
  editForm.supplierPhone = '';
  editForm.productName = '';
  editForm.productUnit = '';
  editForm.unitPrice = 0;
  editForm.purchaseQuantity = 0;
  editForm.purchaseStatusText = '待审批';
};

const submitEditForm = async () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const data = {
          ...editForm,
          purchaseStatus: getStatusCodeFromText(editForm.purchaseStatusText)
        };
        console.log('开始提交修改表单，表单数据:', data);
        const response = await request.post('/purchase_record/updatePurchaseRecord', data);
        console.log('修改表单提交成功，响应数据:', response.data);
        if (response.code === 1) {
          ElMessage.success('修改成功');
          closeEditDialog();
          fetchPurchaseList();
        } else {
          ElMessage.error('修改失败')
          }
        } catch (error) {
          ElMessage.error('修改失败');
          console.error('修改失败:', error);
        }
      }
    });
  };

  // 处理采购状态更改
  const handleStatusChange = async (row) => {
    try {
      const statusCode = getStatusCodeFromText(row.purchaseStatusText);
      const response = await request.put('/purchase_record/updateStatus', {
        purchaseId: row.purchaseId,
        purchaseStatus: statusCode
      });
      if ( response.code === 1) {
        ElMessage.success('状态修改成功');
        row.purchaseStatus = statusCode; // 更新本地数据中的状态码
      } else {
        ElMessage.error('状态修改失败');
        // 恢复原状态
        const originalRow = purchaseList.value.find(item => item.purchaseId === row.purchaseId);
        if (originalRow) {
          row.purchaseStatusText = getPurchaseStatusText(originalRow.purchaseStatus);
        }
      }
    } catch (error) {
      ElMessage.error('状态修改失败');
      // 恢复原状态
      const originalRow = purchaseList.value.find(item => item.purchaseId === row.purchaseId);
      if (originalRow) {
        row.purchaseStatusText = getPurchaseStatusText(originalRow.purchaseStatus);
      }
    }
  };

  // 添加函数将状态码转换为文本
  const getPurchaseStatusText = (status) => {
    switch (status) {
      case 0:
      case '0':
        return '待审批';
      case 1:
      case '1':
        return '已审批';
      case 2:
      case '2':
        return '已完成';
      default:
        return '未知状态';
    }
  };

  // 添加函数将文本转换为状态码
  const getStatusCodeFromText = (text) => {
    switch (text) {
      case '待审批':
        return 0;
      case '已审批':
        return 1;
      case '已完成':
        return 2;
      default:
        return null;
    }
  };

  onMounted(() => {
    fetchPurchaseList();
  });
</script>

<style scoped>
.search-form {
  display: flex;
  gap: 5px;
  margin-bottom: 20px;
  align-items: center; /* 垂直居中对齐 */
  flex-wrap: nowrap; /* 禁止元素换行 */
  overflow-x: auto; /* 当内容超出宽度时显示水平滚动条 */
}

/* 日期选择器宽度 */
.search-form > el-date-picker {
  flex: 0 1 200px; 
  min-width: 0;
}

/* 查询按钮宽度 */
.search-form > el-button {
  flex: 0 0 auto; 
}

/* 选择框宽度 */
.search-form > el-select {
  flex: 0 1 150px; 
  min-width: 0;
}

.red-button {
  background-color: #f5222d; /* 红色背景色 */
  color: #fff; /* 白色文字颜色 */
  border: none;
  transition: background-color 0.3s; 
}
.blue-button{
  background-color: #00bfff; /* 蓝色背景色 */
  color: #fff; /* 白色文字颜色 */
  border: none;
  transition: background-color 0.3s; 
}

.red-button:hover {
  background-color: #cf1322; 
}
.blue-button:hover {
  background-color: #009acd; 
}

/* 为弹窗和表单添加基本样式，确保能正常显示 */
.el-dialog {
  min-width: 300px;
  min-height: 200px;
}

.el-form {
  padding: 10px;
}
</style>